from django.shortcuts import render, redirect
from . import models


# Create your views here.

def index(request):
    return render(request, 'index.html')

def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    elif request.method == 'POST':
        context = {
            'message': '',
        }
        username = request.POST.get('username')  # 对应login.html中form表单中的用户名
        password = request.POST.get('password')
        user = models.User.objects.filter(name=username).first()

        if user:
            if user.password == password:
                request.session['is_login'] = True
                request.session['username'] = user.name
                request.session['userid'] = user.id
                return redirect('/index/')
            else:
                context['message'] = '密码错误'
                return render(request, 'login.html', context=context)
        else:
            context['message'] = '账户未注册'
        return render(request, 'login.html', context=context)

def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    elif request.method == 'POST':
        # name password email 是从前端页面接收的
        # username 是从标签里的name获取的
        username = request.POST.get('username')
        password = request.POST.get('password')
        email = request.POST.get('email')

        user = models.User.objects.filter(email=email).first()
        if user:
            return render(request, 'register.html', context={'message': '账户已存在'})

        try:
            user = models.User(name=username, password=password, email=email)
            user.save()
            return render(request, 'login.html', context={'message': '注册成功，请登录'})
        except Exception as e:
            return render(request, 'register.html', context={'message': e})

def logout(request):
    request.session.flush()
    return redirect('/index/')